#!/bin/bash

# This shell script and the accompanying Dockerfile and patch files are used by
# the project maintainers to create the precompiled drake-visualizer binaries
# that are downloaded during the build. They are neither called during the
# build nor expected to be called by most developers or users of the project.

set -eu -o pipefail

salt=$(dd if=/dev/urandom bs=2 count=4 | od -An -x | tr -d ' ')
tag_prefix=drake-visualizer:$(date -u +%Y%m%d%H%M%S)-$salt

declare -a images

trap cleanup EXIT

###############################################################################

cleanup()
{
    [ ${#images[@]} -gt 0 ] && docker image rm "${images[@]}"
}

build()
{
    local tag=${tag_prefix}-$1
    shift 1

    docker build \
        --force-rm --tag $tag \
        "$@" "$(dirname "${BASH_SOURCE}")"
    images+=($tag)
}

extract()
{
    local tag=${tag_prefix}-$1

    docker run --rm $tag \
        bash -c 'tar -cf - /opt/director/dv*.tar.gz{,.sha256}' | \
        tar --strip-components=2 -xf -
}

###############################################################################

rm -f dv-*.tar.gz{,.sha256}

build focal --build-arg PLATFORM=ubuntu:20.04
extract focal
